package com.bestvike.stone.spring.shiro.annotation.resolver;

import com.bestvike.stone.spring.shiro.aop.MethodInvocation;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.ClassUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * Spring 注解解析器
 */
public final class SpringAnnotationResolver implements AnnotationResolver {
    /**
     * 获取方法上的指定类型注解
     */
    @Override
    public Annotation getAnnotation(MethodInvocation methodInvocation, Class<? extends Annotation> clazz) {
        Method method = methodInvocation.getMethod();
        Annotation annotation = AnnotationUtils.findAnnotation(method, clazz);
        if (annotation != null)
            return annotation;
        Class<?> targetClass = methodInvocation.getThis().getClass();
        method = ClassUtils.getMostSpecificMethod(method, targetClass);
        annotation = AnnotationUtils.findAnnotation(method, clazz);
        if (annotation != null)
            return annotation;
        // See if the class has the same annotation
        return AnnotationUtils.findAnnotation(methodInvocation.getThis().getClass(), clazz);
    }
}
